#!/usr/bin/bash

(
  _name=ubuntu

  set_default_files(){
      if [ ! -e "/home/$_name" ];then
        mkdir -p "/home/$_name"
        chown -R $_name:$_name /home/$_name/
      fi

      if [ ! -e "/home/$_name/.bashrc" ] && [ -f "/etc/skel/.bashrc" ];then
        cp "/etc/skel/.bashrc" "/home/$_name/.bashrc"
        echo -e "\n# hello\nexport TZ=Asia/Shanghai\nexport LANG=zh_CN.UTF-8\n" >> "/home/$_name/.bashrc"
        chown -R $_name:$_name "/home/$_name/.bashrc"
      fi

      if [ ! -e "/home/$_name/.config" ];then
        if [ -e /etc/home_config/ ];then
            cp -r /etc/home_config/ /home/$_name/.config
            chown -R $_name:$_name /home/$_name/.config
        fi
      fi
  }

  if [ ! -e "/first_run" ] || [ ! -e "/home/$_name" ];then
    # Create the user account
    _uid=1000
    _pass="$_name"

    if id $_name &>/dev/null;then
      echo "[w] user $_name is already exists,ignore"
    else
      groupadd --gid $_uid $_name
      if [ -e "/home/$_name" ];then
        useradd --shell /bin/bash --uid $_uid --gid $_uid --password $(openssl passwd "$_pass") --home-dir /home/$_name $_name
        chown $_name:$_name "/home/$_name/"
      else
        useradd --shell /bin/bash --uid $_uid --gid $_uid --password $(openssl passwd "$_pass") --create-home --home-dir /home/$_name $_name
      fi
      usermod -aG sudo $_name
    fi

    set_default_files

    (
      if [ -f "/first_run.init.sh" ];then
        bash "/first_run.init.sh" "$_name"
      fi
    )

    chown -R $_name:$_name /home/$_name/
    date > /first_run
  else
    set_default_files
  fi
)

# Start xrdp sesman service
#       # docker restart ; pid file prevent xrdp-seaman startting..
[ ! -f /var/run/xrdp/xrdp-sesman.pid ] || rm -f /var/run/xrdp/xrdp-sesman.pid
[ ! -f /var/run/xrdp/xrdp.pid ] || rm -f /var/run/xrdp/xrdp.pid
/usr/sbin/xrdp-sesman

# Run xrdp in foreground if no commands specified
if [ -z "$1" ]; then
    /usr/sbin/xrdp --nodaemon
else
    /usr/sbin/xrdp
    exec "$@"
fi


